<template>
  <a-card :bordered="false">
      <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="单据编号">
              <j-input placeholder="请输入单据编号" v-model="queryParam.billNo"></j-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="单据类型">
              <j-dict-select-one-tag placeholder="请选择单据类型" v-model="queryParam.billType" dictCode="kingdee_bill_type"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="申请人/报销人">
                <select-user-by-dep
                  placeholder="请选择申请人/报销人"
                  v-model="queryParam.reimburser" />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="本次付款/支付金额">
                <a-input-number placeholder="请输入最小值" class="query-group-cust" :precision="2" v-model="queryParam.paymentAmount_begin" style="width:calc(50% - 15px);"></a-input-number>
                <span class="query-group-split-cust"></span>
                <a-input-number placeholder="请输入最大值" class="query-group-cust" :precision="2" :min="queryParam.paymentAmount_begin" v-model="queryParam.paymentAmount_end" style="width:calc(50% - 15px);"></a-input-number>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="实际支付金额">
                <a-input-number placeholder="请输入最小值" class="query-group-cust" :precision="2" v-model="queryParam.actualPaymentAmount_begin" style="width:calc(50% - 15px);"></a-input-number>
                <span class="query-group-split-cust"></span>
                <a-input-number placeholder="请输入最大值" class="query-group-cust" :precision="2" :min="queryParam.actualPaymentAmount_begin" v-model="queryParam.actualPaymentAmount_end" style="width:calc(50% - 15px);"></a-input-number>
              </a-form-item>
            </a-col>
            <!-- <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="交单状态">
              <j-dict-select-one-tag placeholder="请选择交单状态" v-model="queryParam.recordStatus" dictCode="record_status"/>
            </a-form-item>
          </a-col> -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="付款进度">
              <j-dict-select-one-tag placeholder="请选择付款进度" v-model="queryParam.billSchedule" dictCode="bill_schedule"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-button @click="handleAdd" type="primary" icon="plus" :disabled="isDisabledAuth('erpFinancePaymentAgainstDocumentsRecord:add')">新增</a-button> -->
      <a-button type="primary" icon="download" @click="handleExportXls('财务交单记录表')" :disabled="isDisabledAuth('erpFinancePaymentAgainstDocumentsRecord:export')">导出</a-button>
      <!-- <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import" :disabled="isDisabledAuth('erpFinancePaymentAgainstDocumentsRecord:import')">导入</a-button>
      </a-upload> -->
      <!-- 高级查询区域 -->
      <!--<j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <!-- <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel" :disabled="isDisabledAuth('erpFinancePaymentAgainstDocumentsRecord:delete')"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown> -->
      <a-popover title="自定义列" trigger="click" placement="leftBottom">
        <template slot="content">
          <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
            <a-row>
              <template v-for="(item,index) in defColumns">
                <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                  <a-col :span="12" :key="index"><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col>
                </template>
              </template>
            </a-row>
          </a-checkbox-group>
        </template>
        <a style="float: right;"><a-icon type="setting" :style='iconStyle'/></a>
      </a-popover>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        :components="draggableComponent"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        :customRow="customRow"
        :expandedRowKeys="expandedRowKeys"
        @expand="expand"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">
        <template slot="expandedRowRender" slot-scope="text,record">
          <p style="color:#000"><b>支付进度一览</b></p>
          <a-table
          ref="table"
          size="small"
          :scroll="{x:true}"
           bordered
            :columns="innerColumns"
            :dataSource="innerDataSource"
            :pagination="false"
            :locale="{emptyText: '暂无支付进度，请耐心等待财务为您处理' }"
          >
            <template slot="fileSlot" slot-scope="text">
              <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
              <span v-else-if="text=='ERROR'" style="font-size: 12px;font-style: italic;">电子回单已过期，请联系出纳</span>
              <a-button
                v-else
                :ghost="true"
                type="primary"
                icon="download"
                size="small"
                @click="downloadFile(text)">
                下载
              </a-button>
            </template>
          </a-table>
        </template>
        <a slot="billNo" slot-scope="text, record" @click="getDetail(record)">{{ text }}</a>
      </a-table>
    </div>

    <erp-finance-payment-against-documents-record-modal ref="modalForm" @ok="modalFormOk"></erp-finance-payment-against-documents-record-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import ErpFinancePaymentAgainstDocumentsRecordModal from './modules/ErpFinancePaymentAgainstDocumentsRecordModal'
  import { getAction,postAction } from '@/api/manage'
  import {DisabledAuthFilterMixin} from '@/mixins/DisabledAuthFilterMixin'
  import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'


  export default {
    name: 'ErpFinancePaymentAgainstDocumentsRecordList',
    mixins:[JeecgListMixin, mixinDevice, DisabledAuthFilterMixin],
    components: {
      ErpFinancePaymentAgainstDocumentsRecordModal,
      SelectUserByDep
    },
    data () {
      return {
        description: '财务交单记录表管理页面',
        //表头
        columns:[],
        //列设置
        settingColumns:[],
        innerDataSource:[],
        expandedRowKeys:[],
        // 列定义
        innerColumns:[
        {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'单据编号',
            align:"center",
            width:200,
            ellipsis: true,
            scopedSlots: {customRender: 'billNo'},
            dataIndex: 'billNo',
          },
          {
            title:'本次付款金额(元)',
            align:"center",
            width:200,
            ellipsis: true,
            dataIndex: 'paymentAmount',
          },
          {
            title:'实际支付金额(元)',
            align:"center",
            width:200,
            ellipsis: true,
            dataIndex: 'actualPaymentAmount',
          },
          {
            title:'付款进度',
            align:"center",
            width:150,
            ellipsis: true,
            dataIndex: 'billSchedule_dictText',
          },
          {
            title:'支付方式',
            align:"center",
            width:150,
            ellipsis: true,
            dataIndex: 'billPayType_dictText',
          },
          {
            title:'银行电子回单',
            align:"center",
            width:200,
            ellipsis: true,
            dataIndex: 'attachment',
            scopedSlots: {customRender: 'fileSlot'},
          },
        ],
        defColumns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'单据编号',
            align:"center",
            width:200,
            ellipsis: true,
            scopedSlots: {customRender: 'billNo'},
            dataIndex: 'billNo',
          },
          {
            title:'单据分类',
            align:"center",
            width:200,
            ellipsis: true,
            dataIndex: 'billType_dictText'
          },
          {
            title:'申请人/报销人',
            align:"center",
            width:200,
            ellipsis: true,
            dataIndex: 'reimburser_dictText',
          },
          {
            title:'本次付款/支付金额(元)',
            align:"center",
            width:180,
            ellipsis: true,
            dataIndex: 'paymentAmount',
          },
          {
            title:'实际支付总金额(元)',
            align:"center",
            width:180,
            ellipsis: true,
            dataIndex: 'actualPaymentAmount',
          },
          {
            title:'剩余未支付金额(元)',
            align:"center",
            width:180,
            ellipsis: true,
            dataIndex: 'remainingPaymentAmount',
          },
          {
            title:'交单状态',
            align:"center",
            width:150,
            ellipsis: true,
            dataIndex: 'recordStatus_dictText',
          },
          {
            title:'交单时间',
            align:"center",
            width:180,
            ellipsis: true,
            dataIndex: 'againstDocumentsTime',
          },
        ],
        url: {
          list: "/api/erp/finance/record/erpFinancePaymentAgainstDocumentsRecord/list",
          delete: "/api/erp/finance/record/erpFinancePaymentAgainstDocumentsRecord/delete",
          deleteBatch: "/api/erp/finance/record/erpFinancePaymentAgainstDocumentsRecord/deleteBatch",
          exportXlsUrl: "/api/erp/finance/record/erpFinancePaymentAgainstDocumentsRecord/exportXls",
          importExcelUrl: "/api/erp/finance/record/erpFinancePaymentAgainstDocumentsRecord/importExcel",
        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
      //加载数据字典信息
      this.getSuperFieldList();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      expand(expanded,record) {
        console.log(expanded,record)
        this.expandedRowKeys = []
      // 只展开一行
        if (expanded) {
          //进这个判断说明当前已经有展开的了
          //返回某个指定的字符串值在字符串中首次出现的位置，下标为0
          let index = this.expandedRowKeys.indexOf(record.id)
          if (index > -1) {
            //如果出现则截取这个id,1d到1相当于0，针对重复点击一个
            this.expandedRowKeys.splice(index, 1)
          } else {
            //如果没出现则截取所有id,添加点击id，0到1，针对已经有一个展开，点另一个会进入判断
            this.expandedRowKeys.splice(0, this.expandedRowKeys.length)
            this.expandedRowKeys.push(record.id)
            this.innerDataSource=this.dataSource.filter(item=>item.id==record.id)[0].child;
          }
        } else {
          //数组长度小于0，说明都没展开，第一次点击，id添加到数组，数组有谁的id谁就展开
          //this.expandedRowKeys.push(record.id)
        }

    },
      loadData(arg) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        var params = this.getQueryParams() // 查询条件
        params.recordStatus = 'success,fail'
        this.loading = true
        getAction(this.url.list, params).then(res => {
          if (res.success) {
            // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            //判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1);
            }
            // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.dataSource = [];
            this.ipagination.total = 0
            this.$message.warning(res.message)
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        }).catch(err => {
          this.$message.warning(err.message)
        })
      },
      //查看详情
      getDetail(record) {
        console.log(record)
          const _path = this.$route.path
        if (_path.startsWith('/hmhb/') || _path.startsWith('/scy/') || _path.startsWith('/imp/')
          || _path.startsWith('/erp/')) {
          this.$router.push({
            path: `${_path}Detail/${record.billType}&${record.billId}`
          })
        } else {
          this.$refs.modalForm.edit(record);
          this.$refs.modalForm.title = '详情';
          this.$refs.modalForm.disableSubmit = true;
        }
      },
      handleDetail: function (record) {
        const _path = this.$route.path
        // console.log('path========', _path)

        //debugger;
        if (_path.startsWith('/hmhb/') || _path.startsWith('/scy/') || _path.startsWith('/imp/')
          || _path.startsWith('/erp/')) {
          this.$router.push({
            path: `${_path}Detail/${record.billType}&${record.billId}`
          })
        } else {
          this.$refs.modalForm.edit(record);
          this.$refs.modalForm.title = '详情';
          this.$refs.modalForm.disableSubmit = true;
        }
        //   console.log(this.$route)
      },
      initDictConfig(){
        //人员
        initDictOptions('erp_employee_file,name,id').then(async(res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'reimburser', res.result)
          }
        })
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'billNo',text:'单据编号',dictCode:''})
        fieldList.push({type:'string',value:'billType',text:'单据类型',dictCode:''})
        fieldList.push({type:'string',value:'billId',text:'单据主键',dictCode:''})
        fieldList.push({type:'string',value:'companyId',text:'公司id',dictCode:''})
        fieldList.push({type:'string',value:'reimburser',text:'报销人',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'paymentAmount',text:'支付金额',dictCode:''})
        fieldList.push({type:'string',value:'presenter',text:'交单人',dictCode:''})
        fieldList.push({type:'date',value:'againstDocumentsTime',text:'交单时间'})
        fieldList.push({type:'Text',value:'attachment',text:'回单附件',dictCode:''})
        fieldList.push({type:'string',value:'billSchedule',text:'单据进度',dictCode:''})
        fieldList.push({type:'string',value:'billStatus',text:'单据状态',dictCode:''})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
